package com.dbapp.garden.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class IPUtil {

	public static long getEndCRange(String ip) {
		StringBuffer sb = new StringBuffer();
		String value[] = ip.split("\\.");
		for (int i = 0; i < value.length - 1; i++) {
			sb.append(value[i]).append(".");
		}
		sb.append("255");
		return IPUtil.ipToLong(sb.toString());
	}

	public static long getEndCRange(long ip) {
		return getEndCRange(IPUtil.longToIP(ip));
	}

	public static long getStartCRange(String ip) {
		StringBuffer sb = new StringBuffer();
		String value[] = ip.split("\\.");
		for (int i = 0; i < value.length - 1; i++) {
			sb.append(value[i]).append(".");
		}
		sb.append("0");
		return IPUtil.ipToLong(sb.toString());
	}

	private static String fillStr(String str, int length, String filestr) {
		String newstr = str;
		if (str.length() < length) {
			for (int i = 0; i < length - str.length(); i++) {
				newstr = "0" + newstr;
			}
		}
		return newstr;
	}

	public static boolean checkip(String ip) {
		ip = ip.trim();
		String value[] = ip.split("\\.");
		if (value.length < 4)
			return false;
		for (int i = 0; i < value.length; i++) {
			try {
				if (Integer.parseInt(value[i].trim()) > 255 || Integer.parseInt(value[i].trim()) < 0)
					return false;
			} catch (Exception e) {
				return false;
			}
		}
		return checkInnerIp(ip);
	}

	public static boolean checkipRangeTooBig(String start_ip, String end_ip) {
		if (!checkip(start_ip) || !checkip(end_ip))
			return false;
		String value1[] = start_ip.split("\\.");
		String value2[] = end_ip.split("\\.");
		if (!value1[0].equals(value2[0]) || !value1[1].equals(value2[1]))
			return false;
		return true;
	}

	public static boolean checkInnerIp(String ip) {
		if (ip.startsWith("10"))
			return false;
		if (ip.startsWith("192.168"))
			return false;
		long lstart = IPUtil.ipToLong("172.16.0.0");
		long lend = IPUtil.ipToLong("172.31.255.255");
		long lValue = IPUtil.ipToLong(ip);
		if (lValue >= lstart && lValue <= lend)
			return false;
		return true;
	}

	public static String queryIP(String ip) {
		if (ip == null || ip.equals(""))
			return "";
		else {
			String newip = "";
			String value[] = ip.split("\\.");
			for (int i = 0; i < value.length; i++) {
				newip = newip + fillStr(value[i], 3, "0") + ".";
			}
			return newip.substring(0, newip.length() - 1);
		}
	}

	// 判断是否是mac地址
	public static boolean isMac(String value) {
		boolean result = false;
		do {
			if (null == value || "".equals(value.trim()))
				break;
			value = value.trim();
			try {
				result = value.matches(
						"[a-fA-F\\d]{2}[:-]{1}[a-fA-F\\d]{2}[:-]{1}[a-fA-F\\d]{2}[:-]{1}[a-fA-F\\d]{2}[:-]{1}[a-fA-F\\d]{2}[:-]{1}[a-fA-F\\d]{2}");
			} catch (PatternSyntaxException ex) {
			}
		} while (false);
		return result;
	}

	// mac地址转整数
	public static long macToLong(String mac) {
		if (null == mac || "".equals(mac.trim()))
			return 0;
		mac = mac.trim();
		mac = mac.replace("-", "");
		mac = mac.replace(":", "");
		return Long.parseLong(mac, 16);
	}

	public static String longToMac(long longMac) {
		String strMac = Long.toHexString(longMac);
		while (strMac.length() < 12) {
			strMac = "0" + strMac;
		}
		String mac = "";
		for (int i = 0; i < strMac.length(); i = i + 2) {
			if (mac.equals("")) {
				mac = strMac.substring(i, 2);
			} else {
				mac = mac + ':' + strMac.substring(i, i + 2);
			}
		}
		return mac;
	}

	// 将127.0.0.1形式的IP地址转换成十进制整数，这里没有进行任何错误处理
	public static long ipToLong(String strIp) {
		if (null == strIp || "".equals(strIp.trim()))
			return 0;
		long[] ip = new long[4];
		// 先找到IP地址字符串中.的位置
		int position1 = strIp.indexOf(".");
		int position2 = strIp.indexOf(".", position1 + 1);
		int position3 = strIp.indexOf(".", position2 + 1);
		// 将每个.之间的字符串转换成整型
		ip[0] = Long.parseLong(strIp.substring(0, position1));
		ip[1] = Long.parseLong(strIp.substring(position1 + 1, position2));
		ip[2] = Long.parseLong(strIp.substring(position2 + 1, position3));
		ip[3] = Long.parseLong(strIp.substring(position3 + 1));
		return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
	}

	// 将十进制整数形式转换成127.0.0.1形式的ip地址
	public static String longToIP(long longIp) {
		StringBuffer sb = new StringBuffer("");
		// 直接右移24位
		sb.append(String.valueOf((longIp >>> 24)));
		sb.append(".");
		// 将高8位置0，然后右移16位
		sb.append(String.valueOf((longIp & 0x00FFFFFF) >>> 16));
		sb.append(".");
		// 将高16位置0，然后右移8位
		sb.append(String.valueOf((longIp & 0x0000FFFF) >>> 8));
		sb.append(".");
		// 将高24位置0
		sb.append(String.valueOf((longIp & 0x000000FF)));
		return sb.toString();
	}

	// 从字符串中获取匹配的IP地址
	public static List<String> getMatchIps(String value) {
		List<String> list = new ArrayList<String>();
		do {
			if (null == value || "".equals(value.trim()))
				break;
			value = value.trim();
			try {
				Pattern regex = Pattern
						.compile("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
				Matcher regexMatcher = regex.matcher(value);
				while (regexMatcher.find()) {
					list.add(regexMatcher.group());
				}
			} catch (PatternSyntaxException ex) {

			}
		} while (false);
		return list;
	}

	// 判断是否是IP地址
	public static boolean isIp(String value) {
		boolean result = false;
		do {
			if (null == value || "".equals(value.trim()))
				break;
			value = value.trim();
			try {
				result = value.matches(
						"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
			} catch (PatternSyntaxException ex) {
			}
		} while (false);
		return result;
	}

	// 判断IP地址是否是：192.168.21.*(就是最后一段是*)
	public static boolean isIps(String value) {
		boolean result = false;
		do {
			if (null == value || "".equals(value.trim()))
				break;
			value = value.trim();
			try {
				result = value.matches("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}\\*$");
			} catch (PatternSyntaxException ex) {
			}
		} while (false);
		return result;
	}

	// 判断是否有两个IP地址连在一起
	public static boolean isTwoIp(String value) {
		boolean result = false;
		do {
			if (null == value || "".equals(value.trim()))
				break;
			value = value.trim();
			try {
				Pattern regex = Pattern.compile("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(\\d*)\\.");
				Matcher regexMatcher = regex.matcher(value);
				while (regexMatcher.find()) {
					result = true;
				}
			} catch (PatternSyntaxException ex) {

			}
		} while (false);
		return result;
	}

	public static String split() {
		String filename = "22q";
		// System.out.println(filename);
		// String[] strarray=filename.split("\\.");
		// for (int i = 0; i < strarray.length; i++)
		// System.out.println(strarray[i]);
		return filename.split("\\.")[0];
	}

	public static void zip() throws Exception {
		byte[] buffer = new byte[1024];
		// 生成的ZIP文件名为Demo.zip

		String strZipName = "e:/demo.zip";
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));

		// 需要同时下载的两个文件result.txt ，source.txt
		File[] file1 = { new File("e:/1.jpg"), new File("e:/2.jpg"), new File("e:/22.jpg"), new File("e:/22.png") };
		for (int i = 0; i < file1.length; i++) {
			FileInputStream fis = new FileInputStream(file1[i]);
			out.putNextEntry(new ZipEntry(file1[i].getName()));
			int len;
			// 读入需要下载的文件的内容，打包到zip文件
			while ((len = fis.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			out.closeEntry();
			fis.close();
		}
		out.close();
		// System.out.println("生成Demo.zip成功");
	}

	private static Random ran = new Random();

	public static String createRandomCode(int randomCodeLen, boolean hasLetter) {
		StringBuilder result = null;
		if (randomCodeLen >= 1) {
			result = new StringBuilder();
			if (hasLetter) {
				for (int i = 0; i < randomCodeLen; i++) {
					int random = ran.nextInt(2);
					switch (random) {
					case 0:
						result.append(createRandomNum());
						break;
					case 1:
						result.append(createRandomLowerLetter());
						break;
					case 2:
						result.append(createRandomUpperLetter());
						break;
					}
				}
			} else if (!hasLetter) {
				for (int i = 0; i < randomCodeLen; i++) {
					result.append(createRandomNum());
				}
			}
			return result.toString();
		}
		return null;
	}

	private static String createRandomNum() {
		return String.valueOf(ran.nextInt(10));
	}

	private static String createRandomLowerLetter() {
		int a = 97;
		int random = a + ran.nextInt(26);
		return String.valueOf((char) (byte) random);
	}

	private static String createRandomUpperLetter() {
		byte A = 65;
		int random = A + ran.nextInt(26);
		return String.valueOf((char) (byte) random);
	}

	public static void main(String args[]) {
		// String a="192.168.50.135";
		// System.out.println(IPUtil.ipToLong(a));
		// System.out.println(split());
		/*
		 * try { zip(); } catch (Exception e) { e.printStackTrace(); }
		 */
		// String temp = "/usr/local/apache-tomcat-7.0.54/webapps/ROOT/";
		// System.out.println(temp.substring(0, temp.length()-6));
	}
}
